package cn.ava.pet.service.impl;

import cn.ava.basic.exception.BusinessException;
import cn.ava.basic.utils.*;
import cn.ava.order.domain.OrderPetAcquisition;
import cn.ava.order.mapper.OrderPetAcquisitionMapper;
import cn.ava.org.domain.Employee;
import cn.ava.org.domain.Shop;
import cn.ava.org.mapper.EmployeeMapper;
import cn.ava.org.mapper.ShopMapper;
import cn.ava.pet.domain.Pet;
import cn.ava.pet.domain.SearchMasterMsg;
import cn.ava.pet.domain.SearchMasterMsgAuditLog;
import cn.ava.pet.domain.SearchMasterMsgRejectLog;
import cn.ava.pet.dto.AcceptOrderDto;
import cn.ava.pet.mapper.PetMapper;
import cn.ava.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.ava.pet.mapper.SearchMasterMsgMapper;
import cn.ava.pet.mapper.SearchMasterMsgRejectLogMapper;
import cn.ava.pet.service.ISearchMasterMsgService;
import cn.ava.basic.service.impl.BaseServiceImpl;
import cn.ava.user.domain.Logininfo;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ava
 * @since 2022-07-19
 */
@Service
// 开启事务 只读属性和支持事务
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private SearchMasterMsgRejectLogMapper searchMasterMsgRejectLogMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * @Title: publish
     * @Description: 寻主消息业务逻辑处理
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/19 16:27
     * @param:
     * @return:
     */
    @Override
    @Transactional
    public void publish(SearchMasterMsg searchMasterMsg) {
        // 直接保存宠物信息,后续用户可以通过个人中心进行修改
        searchMasterMsgMapper.add(searchMasterMsg);
        // 拼接用户信息,方便一次审核
        StringBuilder sb = new StringBuilder();
        sb.append(searchMasterMsg.getTitle())
                .append(searchMasterMsg.getName())
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getCoatColor());
        StringBuilder sbr = new StringBuilder();
        // 审核用户信息是否违规,调用百度Ai智能审核
        if (!BaiDuAiCensorUtil.TextCensor(sb.toString())) {
            sbr.append("宠物名字违规,违规信息: 可能是标题,名字,颜色,地址");
        }
        if (sbr.length() > 0) { // 如果sb大于0,说明有违规信息,添加进审核日志表中
            SearchMasterMsgAuditLog msg = new SearchMasterMsgAuditLog();
            msg.setMsgId(searchMasterMsg.getId());
            msg.setAuditTime(new Date());
            msg.setNote(sbr.toString());
            searchMasterMsgAuditLogMapper.add(msg);
        }else { // 否则就是审核通过
            // 设置为审核通过状态
            searchMasterMsg.setState(1);
            // 调用经纬度工具类,获取地址精度
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 获取到所有店铺
            List<Shop> shops = shopMapper.loadAll();
            Shop shop = DistanceUtil.getNearestShop(point, shops);
            // 如果店铺不为空,说明附近五十公里存在店铺
            if (shop != null){
                // 设置店铺id
                searchMasterMsg.setShopId(shop.getId());
            }
        }
        // 最后修改
        searchMasterMsgMapper.update(searchMasterMsg);
    }

    /**
     * @Title: reject
     * @Description: 拒绝收购单处理
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/20 18:49
     * @param:
     * @return:
     */
    @Override
    public void reject(Long id, HttpServletRequest request) {
        // 获取到当前登录人信息
        Logininfo loginUser = LoginContext.getLoginUser(request);
        // 非空校验
        if (id == null || loginUser == null) {
            throw new BusinessException("订单不存在!");
        }
        // 获取到员工信息
        Employee employee = employeeMapper.getByLogininfoId(loginUser.getId());
        // 获取到当前宠物信息
        SearchMasterMsg msg = searchMasterMsgMapper.getById(id);
        // 设置shopId为null,放入寻主池
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);
        // 保存拒单日志表
        SearchMasterMsgRejectLog log = new SearchMasterMsgRejectLog();
        log.setMsgId(msg.getId());
        log.setUserId(Math.toIntExact(employee.getId()));
        log.setRejectTime(new Date());
        log.setState(1);
        log.setNote("商家拒绝订单!");
        searchMasterMsgRejectLogMapper.add(log);
    }

    /**
     * @Title: accept
     * @Description: 接单处理
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/20 21:55
     * @param:
     * @return:
     */
    @Override
    public void accept(AcceptOrderDto acceptOrderDto) {
        Long handler = acceptOrderDto.getHandler();
        Long msgId = acceptOrderDto.getMsgId();
        String note = acceptOrderDto.getNote();
        // 非空校验
        CheckCodeUtil.checkEmpty(handler,msgId,note);
        // 根据寻主消息id查询是否有此订单
        OrderPetAcquisition  orderPetAcquisition = orderPetAcquisitionMapper.getByMsgId(msgId);
        if (orderPetAcquisition != null) {
            throw new BusinessException("该订单正在处理!");
        }
        // 获取到当前消息
        SearchMasterMsg msg = searchMasterMsgMapper.getById(msgId);
        // 保持宠物信息
        Pet pet = msg2Pet(msg);
        petMapper.add(pet);
        // 保存订单信息
        orderPetAcquisition = initOrderPetAcquisition(handler, note, msg, pet);
        // 发送延时消息,限制最后处理时间
        rocketMQTemplate.syncSend("delay_order_topic", MessageBuilder.withPayload(orderPetAcquisition).build(),3000,3);
        // 添加订单
        orderPetAcquisitionMapper.add(orderPetAcquisition);

    }

    /**
     * @Title: initOrderPetAcquisition
     * @Description: 初始化订单表
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/20 23:51
     * @param:
     * @return:
     */
    private OrderPetAcquisition initOrderPetAcquisition(Long handler, String note, SearchMasterMsg msg, Pet pet) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        orderPetAcquisition.setShopId(msg.getShopId());
        orderPetAcquisition.setSearchMasterMsgId(msg.getId());
        orderPetAcquisition.setPrice(msg.getPrice());
        orderPetAcquisition.setPetId(pet.getId());
        orderPetAcquisition.setAddress(msg.getAddress());
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setDigest(note);
        orderPetAcquisition.setUserId(msg.getUserId());
        orderPetAcquisition.setEmpId(handler);
        // 设置最后处理时间为两天后
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000));
        return orderPetAcquisition;
    }

    /**
     * @Title: msg2Pet
     * @Description: 保存宠物表
     * @Author: Avavaava
     * @Version: 23.53
     * @Date: 2022/7/20 23:51
     * @param:
     * @return:
     */
    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setCreatetime(new Date());
        pet.setSearchMasterMsgId(msg.getId());
        pet.setShopId(msg.getShopId());
        return pet;
    }
}
